package top.kmtec.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import top.kmtec.common.ErrorCode;
import top.kmtec.constant.UserConstant;
import top.kmtec.exception.BusinessException;
import top.kmtec.model.entity.User;
import top.kmtec.service.UserService;
import top.kmtec.mapper.UserMapper;

import java.time.LocalDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author lenovo
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-02-04 09:07:30
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    /**
     * 盐值：混淆密码
     */
    private final String SALT = "wangfenghuan";
    /**
     * 用户注册实现
     * @param account
     * @param password
     * @param checkPassword
     * @return
     */
    @Override
    public long userRegister(String account, String password, String checkPassword, String code) {
        //1、校验
        if (StringUtils.isAllBlank(account, password, checkPassword, code)) {
            // TODO 统一抛出异常
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (account.length() < 4) {
            log.info("用户名长度小于4，注册失败");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名长度小于4");
        }
        if (password.length() < 8 || checkPassword.length() < 8) {
            log.info("用户名长度小于8，注册失败");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名长度小于8");
        }
        //账户不能包含特殊字符
        String regex = "^[\\x20-\\x7E]+$";
        Matcher matcher = Pattern.compile(regex).matcher(account);
        if (!matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户包含特殊字符");
        }
        //校验密码
        if (!password.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入密码不一致");
        }
        //账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", account);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户已经存在");
        }
        //用户编号不能重复
        QueryWrapper<User> queryWrapperCode = new QueryWrapper<>();
        queryWrapperCode.eq("code",code);
        long countCode = this.count(queryWrapperCode);
        if (countCode > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户编号已经存在");
        }
        //对密码进行加密
        String newPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        //向用户数据库插入数据
        User user = User.builder()
                .userAccount(account)
                .password(newPassword)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .code(code)
                .build();
        this.save(user);
        return user.getId();
    }

    /**
     * 用户登录功能实现
     * @param account
     * @param password
     * @param checkPassword
     * @return
     */
    @Override
    public User userLogin(String account, String password, HttpServletRequest request) {
        //1、校验
        if (StringUtils.isAllBlank(account, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号密码不能为空");
        }
        if (account.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户长度小于4");
        }
        if (password.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度小于8");
        }
        //账户不能包含特殊字符
        String regex = "^[\\x20-\\x7E]+$";
        Matcher matcher = Pattern.compile(regex).matcher(account);
        if (!matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户包含特殊字符");
        }
        //对密码进行加密
        String newPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", account);
        queryWrapper.eq("password", newPassword);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            log.info("用户不存在");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        //用户脱敏
        User newUser = User.builder()
                .id(user.getId())
                .userAccount(user.getUserAccount())
                .email(user.getEmail())
                .gender(user.getGender())
                .avatarUrl(user.getAvatarUrl())
                .createTime(user.getCreateTime())
                .userStatus(user.getUserStatus())
                .userRole(user.getUserRole())
                .build();
        //记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATUS, user);
        return user;
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @Override
    public Integer userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATUS);
        return 1;
    }
}




